'''
实验名称：I2C总线(OLED显示屏)
版本：v1.1
日期：2022.4
作者：01Studio
更改yangyu 2024.5
'''
from machine import SoftI2C,Pin         #从machine模块导入I2C、Pin子模块
from ssd1306 import SSD1306_I2C     #从ssd1306模块中导入SSD1306_I2C子模块
from sh1106 import SH1106_I2C     #从sh1106模块中导入SH1106_I2C子模块
from font import fonts
from binascii import hexlify
#OLED输出字符
#OLED=....
#fonts=....
#中文字体16

class oled():

    _oled=None
    # typedriver =1 ssd1306
    # typedriver =2 sh1106
    def __init__(self,typedriver):
        i2c = SoftI2C(sda=Pin(42), scl=Pin(40))   #I2C初始化：sda-->42, scl -->40
        if typedriver == 1:
            #OLED显示屏初始化：128*64分辨率,OLED的I2C地址是0x3c
            self._oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
        elif typedriver == 2:
            #OLED显示屏初始化：128*64分辨率,OLED的I2C地址是0x3c    
            self._oled = SH1106_I2C(128, 64, i2c, addr=0x3c) 
        pass    
    def printf(self,ch_str,x_axis,y_axis):        
        self.chinese(self._oled,ch_str,x_axis,y_axis)
        self._oled.show()
        
    def chinese(self,OLED,ch_str, x_axis, y_axis):
        offset_ = 0 
        y_axis = y_axis*8  # 中文高度一行占8个  
        x_axis = (x_axis*16)  # 中文宽度占16个 
        for k in ch_str:
            
            code = 0x00  # 将中文转成16进制编码 
            data_code = k.encode("utf-8")      
            if (len(data_code)<3):                
                code |= data_code[0]
            else:
                code |= data_code[0] << 16
                code |= data_code[1] << 8
                code |= data_code[2]
            byte_data = fonts[code]
          
            for y in range(0, 16):
                
                a_ = bin(byte_data[y]).replace('0b', '')
                while len(a_) < 8:
                    a_ = '0'+a_
                if(len(byte_data)>16):
                    b_ = bin(byte_data[y+16]).replace('0b', '')
                    while len(b_) < 8:
                        b_ = '0'+b_
                for x in range(0, 8):
                    OLED.pixel(x_axis+offset_+x, y+y_axis, int(a_[x]))
                    if(len(byte_data)>16):
                        OLED.pixel(x_axis+offset_+x+8, y+y_axis, int(b_[x]))
            if(len(byte_data)>16):            
                offset_ += 16
            else:
                offset_ += 8
           
      
